<template>
  <div>
    <el-form ref="ruleForm" :model="form" label-width="80px" :rules="rules"><!---通过rules传入验证规则---->
      <el-form-item prop="username"><!--通过prop传值-->
        <el-input v-model="form.username"  placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          placeholder="请输入密码"
          v-model="form.password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登录</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import axios from "axios";
export default {
  data() {
    return {
      form: {
        username: "admin",
        password: "123456",
      },
      rules:{//表单验证
        username: [
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入用户密码', trigger: 'blur' },
            { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
          ]
        
      }
    };
  },
  methods: {
    onSubmit() {
      let { username, password } = this.form;
      this.$refs.ruleForm.validate(validate=>{//检测表单数据是否符合标准
        if(!validate){//不符合标准弹出警告
           this.$message({
              showClose: true,
              message: "警告，您的表单可能填写有误,请注意提示",
              type: "warning",
            });
        }else if(validate){//符合标准进行请求跳转
          this.userLogin(username,password)
        }
      })
  
      
    },
    userLogin(username,password){//封装请求
      
      this.$req
        .post(`/login`, {
          username,
          password,
        })
        .then((res) => {
          let { data, meta } = res.data;
          if (meta.status === 400) {
            this.$message({
              showClose: true,
              message: "警告哦，这是一条警告消息",
              type: "warning",
            });
          } else if (meta.status === 200) {
            this.$message({
              showClose: true,
              message: "恭喜你，这是一条成功消息",
              type: "success",
            });
            this.$store.commit('userChange',data)
            this.$router.push('/')
          } else {
            this.$message({
              showClose: true,
              message: "错了哦，这是一条错误消息",
              type: "error",
            });
          }
        });
    }
  },
};
</script>

<style>
</style>